package net.expectx.common.single.util;

import java.math.BigInteger;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * OrderUtil
 * @author jianhun
 * @date 2018/5/22
 */
public class OrderUtil {

    /**
     * 订单编号后缀位数
     */
    private static final int SUFFIX_NUMBER = 4;

    private OrderUtil() {

        throw new AssertionError();

    }

    public static String getOrderNo() {

        String prefixNumber = Long.toString(System.currentTimeMillis());
        String suffixNumber = RandomUtil.number(SUFFIX_NUMBER);
        String orderNo = prefixNumber + suffixNumber;
        return orderNo;

    }

    public static String getOrderNo(String memberId, String priceId) {

        StringBuffer sb = new StringBuffer();
        String prefixNumber = Long.toString(System.currentTimeMillis());
        String suffixNumber = RandomUtil.number(SUFFIX_NUMBER);
        sb.append(prefixNumber).append(memberId.charAt((int) (Math.random() * memberId.length())))
                .append(priceId.charAt((int) (Math.random() * priceId.length()))).append(suffixNumber);
        String str = prefixNumber + suffixNumber;
        String orderNo =sb.toString() + new BigInteger(str).remainder(BigInteger.valueOf(9L));
        return orderNo;

    }

    public static String getElectronicSecurity(SortedMap<String, String> packageParams, String key) {

        // 生成电子劵
        String electronicSecurity = createSign(packageParams, key);
        return electronicSecurity;

    }

    /**
     * 获取当前时间戳，单位秒
     * @return
     */
    public static long getCurrentTimestamp() {

        return System.currentTimeMillis()/1000;

    }

    /**
     * 获取当前时间戳，单位毫秒
     * @return
     */
    public static long getCurrentTimestampMs() {

        return System.currentTimeMillis();

    }

    /**
     * 微信支付 生成签名
     * @param packageParams
     * @param key
     * @return
     */
    public static String createSign(SortedMap<String, String> packageParams, String key) {

        StringBuffer sb = new StringBuffer();
        // 字典序
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            // 为空不参与签名、参数名区分大小写
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k).append("=").append(v.trim()).append("&");
            }
        }
        // 第二步拼接key，key设置路径：微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
        sb.append("key=").append(key);
        try {
            String sign = Md5Util.md5(sb.toString()).toUpperCase();
            return sign;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

}
